package com.wwu.system.common.security;

import com.wwu.system.entity.LoginLog;
import com.wwu.system.service.ILoginLogService;
import com.wwu.system.entity.SysUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 登陆失败处理器
 * @author 一蓑烟雨
 * @version 1.0.0
 * @date 2023-06-01 19:04
 */
@Component
public class SecurityLogoutSuccessHandler implements LogoutSuccessHandler {
    @Resource
    private ILoginLogService loginLogService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //记录退出成功日志
        if(!ObjectUtils.isEmpty(authentication)){
            LoginLog loginLog = new LoginLog();
            SysUser sysUser = (SysUser) authentication.getPrincipal();
            loginLog.setSessionId(sysUser.getSessionId());
            loginLog.setLogoutTime(LocalDateTime.now());
            loginLog.setLoginDesc("退出成功");
            long seconds = Duration.between(sysUser.getLoginTime(), LocalDateTime.now()).getSeconds();
            String loginDuration = new DecimalFormat("##0.00").format((float) seconds / 3600);
            loginLog.setLoginDuration(Float.parseFloat(loginDuration));

            loginLogService.updateLoginLog(loginLog);
        }
        response.sendRedirect(request.getContextPath() + "/");
    }
}
